package com.toe.commodity.webapi.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.toe.business.service.BusinessInformationService;
import com.toe.commodity.service.CommodityClassesService;

import com.toe.common.restful.JsonPage;
import com.toe.common.utils.FileUtils;
import com.toe.common.utils.TimeUtil;
import com.toe.pojo.dto.commodity.CommodityClassesDTO;
import com.toe.pojo.entity.business.BusinessInformation;
import com.toe.pojo.entity.commodity.CommodityClasses;
import com.toe.commodity.webapi.mapper.CommodityClassesMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.toe.pojo.entity.user.UserHaveBuy;
import com.toe.pojo.vo.commodity.CommodityClassVO;
import com.toe.pojo.vo.commodity.CommodityOrderClassVO;
import com.toe.pojo.vo.commodity.CommodityUserBuyClassesVO;
import com.toe.user.service.UserHaveBuyService;
import com.toe.user.service.UserHistoryService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 陶涛
 * @since 2022-07-19
 */
@Service
@DubboService
@GlobalTransactional
public class CommodityClassesServiceImpl extends ServiceImpl<CommodityClassesMapper, CommodityClasses> implements CommodityClassesService {

    @Autowired
    private CommodityClassesMapper commodityClassesMapper;

    @DubboReference
    private UserHistoryService dubboUserHistoryService;

    @DubboReference
    private UserHaveBuyService dubboUserHaveBuyService;

    @DubboReference
    private BusinessInformationService dubboBusinessInformationService;

    @Value("${server.port}")
    private String port;

    @Value("${file.staticVideoPatternPath}")
    private String staticVideoPatternPath;

    @Value("${file.staticVideoImgPatternPath}")
    private String staticVideoImgPatternPath;

    @Value("${file.uploadVideoFolder}")
    private String uploadVideoFolder;

    @Override
    public void addNewCommodityClass(CommodityClasses commodityClasses) {
        commodityClassesMapper.addNewCommodityClass(commodityClasses);
    }

    @Override
    public void updateCommodityClass(CommodityClassesDTO commodityClassesDTO) {
        commodityClassesMapper.updateCommodityClass(commodityClassesDTO);
    }

    @Override
    public void deletedCommodityClass(Long id) {
        commodityClassesMapper.deletedCommodityClass(id);
    }

    @Override
    public CommodityClassVO getCommodityClassById(Long id, Long userId) {
        CommodityClassVO commodityClassById = commodityClassesMapper.getCommodityClassById(id);
        if (userId != 0) {
            dubboUserHistoryService.insertHistory(userId, commodityClassById.getId(), 2);
        }
        commodityClassById.setUrl(
                getUrl(staticVideoPatternPath, commodityClassById.getUrl()));
        commodityClassById.setCover(
                getUrl(staticVideoImgPatternPath, commodityClassById.getCover()));
        return commodityClassById;
    }

    @Override
    public List<CommodityClassVO> getCommodityClassByIdList(List<Long> ids) {
        return commodityClassesMapper.getCommodityClassByIds(ids);
    }

    @Override
    public JsonPage<CommodityClassVO> getCommodityClassBySales(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<CommodityClassVO> commodityClassBySales = commodityClassesMapper.getCommodityClassBySales();
        for (CommodityClassVO commodityClassBySale : commodityClassBySales) {
            commodityClassBySale.setUrl(
                    getUrl(staticVideoPatternPath, commodityClassBySale.getUrl()));
            commodityClassBySale.setCover(
                    getUrl(staticVideoImgPatternPath, commodityClassBySale.getCover()));
        }
        return JsonPage.restPage(new PageInfo<>(commodityClassBySales));
    }

    @Override
    public JsonPage<CommodityClassVO> getCommodityClassByBusinessId(Integer pageNum, Integer pageSize, Long id) {
        PageHelper.startPage(pageNum, pageSize);
        List<CommodityClassVO> commodity = commodityClassesMapper.getCommodityClassByBusinessId(id);
        for (CommodityClassVO commodityClassBySale : commodity) {
            commodityClassBySale.setUrl(
                    getUrl(staticVideoPatternPath, commodityClassBySale.getUrl()));
            commodityClassBySale.setCover(
                    getUrl(staticVideoImgPatternPath, commodityClassBySale.getCover()));
        }
        return JsonPage.restPage(new PageInfo<>(commodity));
    }

    // 分页查询根据课程类型查到的课程的方法
    @Override
    public JsonPage<CommodityClassVO> getCommodityClassByClassTypeId(Integer pageNum, Integer pageSize, Long id) {
        PageHelper.startPage(pageNum, pageSize);
        List<CommodityClassVO> commodity = commodityClassesMapper.getCommodityClassByClassTypeId(id);
        for (CommodityClassVO commodityClassBySale : commodity) {
            commodityClassBySale.setUrl(
                    getUrl(staticVideoPatternPath, commodityClassBySale.getUrl()));
            commodityClassBySale.setCover(
                    getUrl(staticVideoImgPatternPath, commodityClassBySale.getCover()));
        }
        return JsonPage.restPage(new PageInfo<>(commodity));
    }

    @Override
    public CommodityOrderClassVO getOrderClassById(Long classId) {
        CommodityOrderClassVO classById =
                commodityClassesMapper.getOrderClassById(classId);
        classById.setUrl(
                getUrl(staticVideoPatternPath, classById.getUrl()));
        classById.setCover(
                getUrl(staticVideoImgPatternPath, classById.getCover()));
        return classById;
    }

    @Override
    public List<CommodityOrderClassVO> listOrderClassesByIds(List<Long> classIds) {
        List<CommodityOrderClassVO> classesByIds =
                commodityClassesMapper.listOrderClassesByIds(classIds);
        for (CommodityOrderClassVO classesById : classesByIds) {
            classesById.setUrl(
                    getUrl(staticVideoPatternPath, classesById.getUrl()));
            classesById.setCover(
                    getUrl(staticVideoImgPatternPath, classesById.getCover()));
        }
        return classesByIds;
    }

    /**
     * 用户购买的课程
     *
     * @param userId
     * @return
     */
    @Override
    public JsonPage<CommodityUserBuyClassesVO> listUserBuyClassesByIds(Long userId, Integer pageNum, Integer pageSize) {
        JsonPage<UserHaveBuy> userHaveBuyJsonPage =
                dubboUserHaveBuyService.listByUserId(userId, pageNum, pageSize);
        List<Long> classIds = new ArrayList<>();
        Map<Long, UserHaveBuy> buyMap = new HashMap<>();
        for (UserHaveBuy userHaveBuy : userHaveBuyJsonPage.getList()) {
            classIds.add(userHaveBuy.getCourseId());
            buyMap.put(userHaveBuy.getCourseId(), userHaveBuy);
        }

        System.out.println("插入的课程id -> " + classIds);
        if (classIds.size() != 0) {
            List<CommodityUserBuyClassesVO> classesByIds =
                    commodityClassesMapper.listUserBuyClassesByIds(classIds);
            List<Long> businessIds = new ArrayList<>();
            for (CommodityUserBuyClassesVO classesById : classesByIds) {
                businessIds.add(classesById.getBusinessId());
            }
            businessIds = businessIds.stream().distinct().collect(Collectors.toList());
            List<BusinessInformation> businessList =
                    dubboBusinessInformationService.listByIds(businessIds);

            Map<Long, String> businessMap = new HashMap<>();
            for (BusinessInformation business : businessList) {
                businessMap.put(business.getId(), business.getName());
            }

            for (CommodityUserBuyClassesVO classesById : classesByIds) {
                String path = uploadVideoFolder + classesById.getUrl();
                classesById.setDurationTime(getDurationTime(path));
                classesById.setUrl(
                        getUrl(staticVideoPatternPath, classesById.getUrl()));
                classesById.setCover(
                        getUrl(staticVideoImgPatternPath, classesById.getCover()));
                classesById.setUserHaveBuyId(buyMap.get(classesById.getId()).getId());
                classesById.setPurchasingTime(
                        TimeUtil.localDateTimeToDate(buyMap.get(
                        classesById.getId()).getCreateTime()));
                classesById.setBusinessName(businessMap.get(classesById.getBusinessId()));
            }

            JsonPage<CommodityUserBuyClassesVO> jsonPage =
                    JsonPage.restPage(new PageInfo<>(classesByIds));
            jsonPage.setPageSize(userHaveBuyJsonPage.getPageSize());
            jsonPage.setPageNum(userHaveBuyJsonPage.getPageNum());
            jsonPage.setTotalPages(userHaveBuyJsonPage.getTotalPages());
            jsonPage.setTotalCount(userHaveBuyJsonPage.getTotalCount());

            return jsonPage;
        }

        return JsonPage.restPage(new PageInfo<>(new ArrayList<>()));
    }

    private String getUrl(String staticPath, String path) {
        return staticPath.split("\\*\\*")[0] + path;
    }

    /**
     * 返回视频时长
     * @param path 路径地址
     * @return hh:mm:ss或mm:ss
     */
    private String getDurationTime(String path) {
        long mp4Duration = FileUtils.getMp4Duration(path);

        String hour = (mp4Duration / 3600) + "";
        hour = hour.length()>1 ? hour : "0"+hour;
        mp4Duration = mp4Duration % 3600;

        String min = (mp4Duration / 60) + "";
        min = min.length()>1 ? min : "0"+min;
        mp4Duration = mp4Duration % 60;

        String sec = mp4Duration + "";
        sec = sec.length()>1 ? sec : "0"+sec;

        return "00".equals(hour) ? min+":"+sec : hour+":"+min+":"+sec;
    }

}
